/**
 * 
 */
package com.jm.web.tags.support;

import java.util.Map;

import com.jm.utils.StringHelper;
import com.jm.web.data.BaseDataEntity;
import com.jm.web.form.Input;
import com.jm.web.form.Option;
import com.jm.web.form.Select;
import com.jm.web.form.Textarea;
import com.jm.web.form.support.FieldItem;
import com.jm.web.form.support.FormItem;

/**
 * @author yanjie
 * 表单使用
 * 2011/9/28 下午12:51:26
 */
public class DataSourceTag extends BaseTag{
	private static final long serialVersionUID = -5719021252706658234L;
	
	private static final String TAG_DATA = "data";
	private static final String TAG_SCOPE = "scope";
	
	protected String strData = "";
	protected String strScope = "";
	protected BaseDataEntity data = null ;
	
	
	public String getData() {
		return strData;
	}
	
	public String getScope() {
		return strScope;
	}
	
	public void setData(String strData) {
		this.strData = strData;
		this.SetExtValue(TAG_DATA, strData);
	}
	
	public void setScope(String strScope) {
		this.strScope = strScope;
		this.SetExtValue(TAG_SCOPE, strScope);
	}
	
	/**
	 * @param item
	 * 填充表单的值
	 */
	public void FillFiledItemValue(FormItem item){
		if(this.getDataSource() == null)
			 return ;
		
		String strParams = item.GetExtValue("params",item.getId());
		if(strParams.length() == 0)
			return ;
		
		String strValue = item.getNodeValue();
		if(strValue.indexOf("%1$s") < 0){
			strValue += "%1$s";
		}
		
		String[] params = strParams.split(",");
		String[] values = new String[params.length];
		
		for (int i = 0; i < params.length; i++) {
			values[i] = this.getDataSource().GetParamStringValue(params[i], "");
		}
		
		item.setNodeValue(StringHelper.Format(strValue,values));
	}
	
	/**
	 * @param item
	 * 填充表单的值
	 */
	public void FillFiledItemValue(FieldItem item){
		if(this.getDataSource() == null)
			 return ;
		
		if(!(item instanceof Input || item instanceof Textarea))
			return ;
		
		if(!StringHelper.IsNullOrEmpty(item.getValue()) && !this.isCheckBoxOrRadio(item))
			return ;
		
		if(this.getDataSource().ContainesParam(item.getName()))
		{
			if(this.getPage().getItemSize(item.getName(),true) == 1)
			{
				//处理表单项名称唯一
				if(this.isCheckBoxOrRadio(item))
				{
					//如果是checkbox or radiao 要设置checked属性
					if(item.getValue().equalsIgnoreCase(this.getDataSource().GetParamStringValue(item.getName(), "")))
					{
						item.SetExtValue("checked", "true");
					}
				}
				else if(item instanceof Textarea)
				{
					//处理textarea 控件的值
					item.setNodeValue(this.getDataSource().GetParamStringValue(item.getName(), ""));
				}
				else
				{
					item.setValue(this.getDataSource().GetParamStringValue(item.getName(), ""));
				}
			}
			else if(this.getPage().getItemSize(item.getName(),true) > 1)
			{	
				//处理表单项名称重复的item
				String args[] = this.getDataSource().GetParamStringValues(item.getName(), null);
				if(args != null && (args.length > item.getIndex() || this.isCheckBoxOrRadio(item))){
					if(this.isCheckBoxOrRadio(item))
					{
						//如果是checkbox or radiao 要设置checked属性
						if(this.arrayContainsKey(args, item.getValue()))
						{
							item.SetExtValue("checked", "true");
						}
					}
					else if(item instanceof Textarea)
					{
						//处理textarea 控件的值
						item.setNodeValue(args[item.getIndex()]);
					}
					else
					{
						item.setValue(args[item.getIndex()]);
					}
				}
			}
		}
	}
	
	public boolean arrayContainsKey(String[] args,String arg){
		if(args == null || args.length == 0)
			return false;
		
		boolean bContain = false;
		for (int i = 0; i < args.length; i++) {
			if(arg.equalsIgnoreCase(args[i])){
				bContain = true ;
				break;
			}
			
		}
		return bContain;
	}
	
	public boolean isCheckBoxOrRadio(FormItem item){
		boolean bIs = false;
		if(item instanceof Input)
		{
			Input input = (Input)item;
			bIs = "checkbox".equalsIgnoreCase(input.getType()) || "radio".equalsIgnoreCase(input.getType());
		}
		return bIs;
	}
	
	/**
	 * @param item
	 * 填充表单的值(下接列表)
	 */
	public void FillFiledItemValue(Option option){
		if(this.getDataSource() == null || StringHelper.IsNullOrEmpty(option.GetExtValue("value", "")))
			return ;
		
		
		Select select = null ;
		if(option.getParentItem() != null && option.getParentItem() instanceof Select){
			select = (Select)option.getParentItem();
		}
		
		if(select == null)
			return ;
		
		if(this.getDataSource().ContainesParam(select.getName()))
		{
			if(this.getPage().getItemSize(select.getName(),true) == 1)
			{
				//处理表单项名称唯一
				if(option.GetExtValue("value", "").equals(this.getDataSource().GetParamStringValue(select.getName(), "")))
				{
					option.SetExtValue("selected", "true");
				}
			}
			else if(this.getPage().getItemSize(select.getName(),true) > 1)
			{
				//处理表单项名称重复的item
				String args[] = this.getDataSource().GetParamStringValues(select.getName(), null);
				if(args != null && args.length > select.getIndex()){
					if(option.GetExtValue("value", "").equals(args[select.getIndex()]))
					{
						option.SetExtValue("selected", "true");
					}
				}
			}
		}
	}
	
	public BaseDataEntity getDataSource(){
		if(StringHelper.IsNullOrEmpty(this.getData()))
			return new BaseDataEntity();
		
		if(this.data == null)
			this.data = new BaseDataEntity();
		else 
			return this.data;
		
		strData = strData.replaceAll(";", ",");
		strData = strData.replaceAll("\\|", ",");
		String datas[] = strData.split(",");
		
		strScope = strScope.replaceAll(";", ",");
		strScope = strScope.replaceAll("\\|", ",");
		String scopes[] = strScope.split(",");
		
		
		for (int i = 0; i < datas.length; i++) {
			String data = datas[i];
			String scope = scopes.length > i ? StringHelper.getValue(scopes[i], "request") : "request";
			
			if(StringHelper.IsNullOrEmpty(data) || StringHelper.IsNullOrEmpty(scope))
				continue;
			
			Object object = null ;
			if("request".equalsIgnoreCase(scope)){
				object = this.getPage().getRequest().getAttribute(data);
			}else if("session".equalsIgnoreCase(scope)){
				object = this.getPage().getRequest().getSession().getAttribute(data);
			}else if("form".equalsIgnoreCase(scope)){
				object = this.getPage().getUtils().getForm().gpov(data);
			}else if("ret".equalsIgnoreCase(scope)){
				object = this.getPage().getUtils().getReturnData().gpov(data);
			}
			
			if(object == null)
				continue;
			
			if(object instanceof BaseDataEntity){
				((BaseDataEntity) object).CopyTo(this.data, false);
			}else if(object instanceof Map){
				this.data.FromMap((Map)object,false);
			}
		}
		
		return this.data;
	}
	
	@Override
	public void clear() {
		this.data = null;
		this.strData = "";
		this.strScope = "";
		super.clear();
	}
}
